package com.xigua.JucOfBeautiful.chapterOne.notifyAndWait1_3;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2022/1/2022:28
 */
public class NotifyTest {
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (resourceA){
                        System.out.println("threadA get resourceA lock");
                        synchronized (resourceB){

                            System.out.println("threadA get resourceB lock");
                            System.out.println("threadA release resourceA lock");
                            resourceA.wait();
                            System.out.println(11);
                            resourceB.wait();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    synchronized (resourceA) {
                        System.out.println("threadB get resourceA lock");
                        System.out.println("threadB try get resourceB lock");
                        resourceA.notifyAll();

                        synchronized (resourceB){
                            System.out.println("threadB get resourceB lock");
                            System.out.println("ThreadB release resourceB lock");
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // 线程调用共享对象的wait方法时，当前线程只会释放当前共享变量的锁。当前线程持有的其他共享对象的监视器并不会释放锁。
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
        System.out.println("main over");

    }

}
